package org.zhtkj.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zhtkj.framework.session.SessionManager;
import org.zhtkj.web.endpoint.JT808Endpoint;
import org.zhtkj.web.jt808.common.JT808MessageCode;
import org.zhtkj.web.jt808.dto.CommonResult;
import org.zhtkj.web.jt808.dto.MediaControl;
import org.zhtkj.web.jt808.dto.MediaPlaybackControl;
import org.zhtkj.web.jt808.dto.MediaPlaybackRequest;
import org.zhtkj.web.jt808.dto.MediaPropQuery;
import org.zhtkj.web.jt808.dto.MediaPropReply;
import org.zhtkj.web.jt808.dto.MediaTransRequest;
import org.zhtkj.web.jt808.dto.MediaTransStatusNotify;
import org.zhtkj.web.jt808.dto.basics.Header;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.ApiOperation;

/**
 * ClassName: TerminalMediaController 
 * @Description: 终端视频控制器
 * @author Nikotesla
 * @date 2019年1月16日
 */
@Controller
@RequestMapping 
public class TerminalMediaController {

	private static final Logger logger = LoggerFactory.getLogger(TerminalMediaController.class);
	
	@Autowired
    private SessionManager sessionManager;
    
    @Autowired
    private JT808Endpoint endpoint;
    
    /**
     * @Description: 实时音视频传输请求
     * @param params
     * @return   
     * @return CommonResult  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "实时音视频传输请求")
    @RequestMapping(value="videoservice/realPlayRequest", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> realPlayRequest(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("实时音视频传输请求in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
		Map<?, ?> msg = (Map<?, ?>) params.get("msg");
    	Integer logicalChn = (Integer) msg.get("logicalChn");
		Integer dataType = (Integer) msg.get("dataType");
		Integer streamType = (Integer) msg.get("streamType");
		String sinkIP = (String) msg.get("sinkIP");
		Integer sinkPort = (Integer) msg.get("sinkPort");
    	MediaTransRequest body = new MediaTransRequest();
    	body.setLength(sinkIP.getBytes().length);
    	body.setIpAddress(sinkIP);
    	body.setTcpPort(sinkPort);
    	body.setUdpPort(0);
    	body.setChannelId(logicalChn);
    	body.setDataType(dataType);
    	body.setCodeType(streamType);
    	body.setHeader(new Header(JT808MessageCode.实时音视频传输请求, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {
    		endpoint.send(body);
    		result.put("resultCode", 0);
    		result.put("resultMsg", "ok");
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
    /**
     * @Description: 音视频实时传输控制
     * @param params
     * @return   
     * @return CommonResult  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "音视频实时传输控制")
    @RequestMapping(value="videoservice/realPlayControl", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> realPlayControl(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("音视频实时传输控制in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
		Map<?, ?> msg = (Map<?, ?>) params.get("msg");
    	Integer logicalChn = (Integer) msg.get("logicalChn");
		Integer ctrlCmd = (Integer) msg.get("ctrlCmd");
		Integer closeAVType = (Integer) msg.get("closeAVType");
		Integer changeStreamType = (Integer) msg.get("changeStreamType");
    	MediaControl body = new MediaControl();
    	body.setLogicalChn(logicalChn);
    	body.setCtrlCmd(ctrlCmd);
    	body.setCloseAVType(closeAVType);
    	body.setChangeStreamType(changeStreamType);
    	body.setHeader(new Header(JT808MessageCode.音视频实时传输控制, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {
    		CommonResult commonResult = (CommonResult) endpoint.send(body, true);
    		result.put("resultCode", commonResult.getResultCode());
    		result.put("resultMsg", "ok");
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
    /**
     * @Description: 实时音视频传输状态通知
     * @param params
     * @return   
     * @return CommonResult  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "实时音视频传输状态通知")
    @RequestMapping(value="videoservice/realPlayNotifyStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> realPlayNotifyStatus(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("实时音视频传输状态通知in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
		Map<?, ?> msg = (Map<?, ?>) params.get("msg");
    	Integer logicalChn = (Integer) msg.get("logicalChn");
		Integer lossRate = (Integer) msg.get("lossRate");
		MediaTransStatusNotify body = new MediaTransStatusNotify();
    	body.setLogicalChn(logicalChn);
    	body.setLossRate(lossRate);
    	body.setHeader(new Header(JT808MessageCode.实时音视频传输状态通知, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {
    		endpoint.send(body, false);
    		result.put("resultCode", 0);
    		result.put("resultMsg", "ok");
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
    /**
     * @Description: 远程录像回放请求
     * @param params
     * @return   
     * @return CommonResult  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "远程录像回放请求")
    @RequestMapping(value="videoservice/playbackRequest", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> playbackRequest(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("远程录像回放请求in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
		Map<?, ?> msg = (Map<?, ?>) params.get("msg");
		String sinkIP = (String) msg.get("sinkIP");
		Integer sinkPort = (Integer) msg.get("sinkPort");
    	Object logicalChn = msg.get("logicalChn");
    	Object resourceType = msg.get("resourceType");
    	Object streamType = msg.get("streamType");
    	Object storageType = msg.get("storageType");
    	Object replayType =msg.get("replayType");
    	Object multiples = msg.get("multiples");
    	Object beginTime = msg.get("beginTime");
    	Object endTime = msg.get("endTime");
		MediaPlaybackRequest body = new MediaPlaybackRequest();
		body.setLength(sinkIP.getBytes().length);
		body.setIpAddress(sinkIP);
		body.setTcpPort(sinkPort);
		body.setUdpPort(0);
    	body.setLogicalChn(logicalChn == null ? null : (Integer) logicalChn);
    	body.setMediaType(resourceType == null ? null : (Integer) resourceType);
    	body.setStreamType(streamType == null ? null : (Integer) streamType);
    	body.setStorageType(storageType == null ? null : (Integer) storageType);
    	body.setReplayType(replayType == null ? null : (Integer) replayType);
    	body.setMultiples(multiples == null ? null : (Integer) multiples);
    	body.setStartTime(beginTime == null ? null : DateTime.parse((String) beginTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toString("yyyyMMddHHmmss").substring(2, 14));
    	body.setEndTime(endTime == null ? null : DateTime.parse((String) endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toString("yyyyMMddHHmmss").substring(2, 14));
    	body.setHeader(new Header(JT808MessageCode.远程录像回放请求, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {
    		endpoint.send(body);
    		result.put("resultCode", 0);
    		result.put("resultMsg", "ok");
    		//result.put("records", response.getResourceList());
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
    /**
     * @Description: 远程录像回放控制
     * @param params
     * @return   
     * @return MediaPlaybackReply  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "远程录像回放控制")
    @RequestMapping(value="videoservice/playbackControl", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> playbackControl(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("远程录像回放控制in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
		Map<?, ?> msg = (Map<?, ?>) params.get("msg");
    	Object logicalChn = msg.get("logicalChn");
    	Object ctrlCmd = msg.get("ctrlCmd");
    	Object multiples = msg.get("multiples");
    	
    	Object replayLocation = msg.get("replayLocation");
		MediaPlaybackControl body = new MediaPlaybackControl();
		body.setChannelId(logicalChn == null ? null : (Integer) logicalChn);
		body.setCtrlCmd(ctrlCmd == null ? null : (Integer) ctrlCmd);
    	body.setMultiples(multiples == null ? null : (Integer) multiples);
    	body.setReplayLocation(!StringUtils.isNotEmpty((String) replayLocation) ? null : DateTime.parse((String) replayLocation, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toString("yyyyMMddHHmmss").substring(2, 14));
    	body.setHeader(new Header(JT808MessageCode.远程录像回放控制, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {
    		endpoint.send(body);
    		result.put("resultCode", 0);
    		result.put("resultMsg", "ok");
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
    /**
     * @Description: 查询终端音视频属性
     * @param params
     * @return   
     * @return MediaPropReply  
     * @throws
     * @author Nikotesla
     * @date 2019年1月16日
     */
    @ApiOperation(value = "查询终端音视频属性")
    @RequestMapping(value = "videoservice/getAVideoAttributes", method = RequestMethod.POST)
    public Map<String, Object> getAVideoAttributes(@RequestBody Map<String, Object>  params) {
    	try {
			logger.info("查询终端音视频属性in,params:{}", new ObjectMapper().writeValueAsString(params));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	String mobileNumber = (String) params.get("mobileNumber");
    	MediaPropQuery body = new MediaPropQuery();
    	body.setHeader(new Header(JT808MessageCode.查询终端音视频属性, mobileNumber));
    	//返回响应结果
    	Map<String, Object> result = new HashMap<String, Object>();
    	if (sessionManager.findByTerminalId(mobileNumber) != null) {									
    		MediaPropReply response = (MediaPropReply) endpoint.send(body);
    		result.put("resultCode", 0);
    		result.put("resultMsg", "ok");
    		result.put("aVideoAttributes", response);
    	} else {
    		result.put("resultCode", 1);
    		result.put("resultMsg", "terminal offline");
    	}
    	return result;
    }
    
}
